// JavaScript Document

var media = {

	init: function() {
        // initialise the Pane UI JS Library
		paneUI.init({
			contentName: 'Media',
			ajax_page: $p("#ajax_url").val(),
			
            onEditorLoaded: function() {
                media.bindListeners();
            }
		});
        
        $p(".delete-link").bind('click', function() {
            var id = $p(this).attr('data-id');
            
            $p.showConfirmMessage({
               'title': 'Confirm Delete Media Items',
               'content': 'You Are About To Delete The Selected Media File. Do You Want To Continue?',
               okButtonText: 'Continue Delete',
               okButtonAction: function() {
                   
				   var query = "action=delete_media&id=" + id;
                   $p.get( paneUI.ajax_page, query, function() {
                       $p("#media-row-" + id).remove();
                   });
               }
            });
        });
	},
	
	bindListeners: function() {
		
		document.getElementById("media-form").onsubmit = function() {
			return false;	
		};
		
		// make the add or save button process the form
        if( paneUI.editorState == 'add' ) {
            $p("#media-add-btn").val("Add Media").bind('click',function() {
                media.addMedia();
            });
        } else {
            $p("#media-add-btn").val("Save Changes").bind('click',function() {
                media.updateMedia();
            });
        }
		
		// make the cancel button hide the paneUI editor
        $p("#media-cancel-btn").bind("click", function() {
            paneUI.hideItemEditor();
        });
		
		$p('#MediaSize').bind('change',function() {
			var value = this.options[this.selectedIndex].value;
			
			if( value != null ) {
				var parts = value.split("x");
				var w = parts[0];
				var h = parts[1];
				
				$p("#MediaWidth").val(w);
				$p("#MediaHeight").val(h);
			} else {
				$p("#MediaWidth").val("320");
				$p("#MediaHeight").val("240");
			}
		});
		
		// attach a change event handler to the Category field
		$p('#MediaCategory').bind('change', function() {
			var value = this.value;
			document.getElementById("uploadFile").disabled = value == '';	
		});
		
		// initialize the Picture Frame and Uploader
		picup.init({
			targetDiv : "picupArea",
			imgPath : $p("#MediaThumbnail").val(),
			/*pictureField : "Picture",*/
			thumbField : "MediaThumbnail",
			destFolder : "../assets/images/content/pics/",
			thumbFolder : "../assets/images/content/thumbs/",
			useSection: "media"
		});
		
		// attach a handler to the uploadFile field if it exists
        $p('#uploadFile').bind('change', function() {
			
			var field = this;
			var mediaPath = document.getElementById("MediaPath");
			var folderObj = document.getElementById("mediaDestFolder");
			var destFileName = document.getElementById("destFileName");
			var imageFile = document.getElementById("ImageFile");
			
			if(mediaPath != null) {
				var fileName = field.value;
				var ext = fileName.substring( fileName.lastIndexOf(".") );
				var mediaTypeSelected = selectMediaType(ext);									
				
				if( !mediaTypeSelected ) {
					return;	
				}
				
				var now = new Date();
				var dateStr = now.getFullYear() + "" + (now.getMonth() + 1) + "" + now.getDate() + "_" + now.getHours() + "" + now.getMinutes() + "" + now.getSeconds();
				folderObj.value = "../assets/media/" + ext.substring(1) + "/";
				destFileName.value = "media" + dateStr;
				imageFile.value = "media" + dateStr + ext;
				
				mediaPath.value = folderObj.value + destFileName.value + ext;
			}
            
			var category = document.getElementById("MediaCategory").value;
            var dstFolder = "../assets/media/" + category + "/";
            var file_path = document.getElementById("uploadFile").value;
			
			// calculate the data time to be used as the destination file name
			var now = new Date();
            var dateStr = now.getFullYear() + "" + (now.getMonth() + 1) + "" + now.getDate() + "_" + now.getHours() + "" + now.getMinutes() + "" + now.getSeconds();
			document.getElementById('destFileName').value = "media" + dateStr;
			document.getElementById("destFolder").value = dstFolder;
			
			// generate the destination file name to used for the picture field
            //file_utils.generateDestinationFileName('url', dstFolder, file_path, 'media');
			
			//alert( dstFolder + "\n" + document.getElementById('url').value );
        });
		
		$("#file_browser").fileTree({
			script: 'scripts/jqueryFileTree/connectors/jqueryFileTree.php',
			root: "/"
		}, function(file) {
			$("#MediaPath").val( "../assets" + file );
			$("#uploadFile").val(null);
			$("#file_browser_container").hide('slow');
		});
		
		$(".file_finder").click(function(e) {
			e.preventDefault();
			
			$("#file_browser_container").css({
				left: '50%',
				top: '500px'	
			}).show('slow');
		});
		
		$p(".closer a").bind('click', function() {
			$("#file_browser_container").hide('slow');
		});
		
	},
	
	addMedia: function() {
		var valid = $p("#media-form").validate({
            'MediaCategory': 'Please Select A Category For The Media',
            'MediaName': 'Please Provide A Name For This Media',
            'Description': 'Please Provide A Valid Description For The Media',
            'uploadFile': 'Select The File To Be Uploaded'
        });

        if( !valid ) {
            return;
        }
        
        var form = document.getElementById("media-form");

        $p.postMultiPartForm( paneUI.ajax_page, form, null, function(data) {
            
            var data = $p.parseJSON(data);

            paneUI.hideItemEditor();

            // reload the current category of articles
            var selected_cat_id = $p("#media-form #MediaCategory").val();
            var link = paneUI.getCategoryLink(selected_cat_id);
            paneUI.loadItems( link );
        });
	},
	
	updateMedia: function() {
		var valid = $p("#media-form").validate({
            'MediaCategory': 'Please Select A Category For The Download',
            'MediaName': 'Please Provide A Name For This Download',
            'Description': 'Please Provide A Valid Description For The Download'
        });

        if( !valid ) {
            return;
        }

        var query = $p("#media-form").serialize();
        
        $p.post( paneUI.ajax_page, query, function() {
            paneUI.hideItemEditor();
            
            paneUI.reloadItems();
        });
	}
};

pageManager.addLoadEvent( function() {
	media.init();
});

	
function selectMediaType(ext) {
	var typeMenu = document.getElementById("MediaType");
	var menuOptions = typeMenu.options;
	for(var i = 0; i < menuOptions.length; i++) {
		if( menuOptions[i].value == ext.substring(1).toLowerCase() ) {
			typeMenu.selectedIndex = i;
			return true;
		}
	}
	
	alert("The Selected File Is Not A Supported Format"); 
	return false;
}